<template>
  <div class="weui-cell">
    <div class="weui-cell__bd">
      <div class="weui-uploader">
        <div v-show="showHeader" class="weui-uploader__hd">
          <p class="weui-uploader__title"> {{ title }} </p>
          <div class="weui-uploader__info">
            {{ imageData.length }} / {{ max }}
          </div>
        </div>
        <div :class="{small: size === 'small'}">
          <div v-show="imageData.length >= max" style="width: 1.875rem; height: 1.875rem; display: inline-block;" @click="addImage()">
            <label class="uploadHead" for="upHead1" v-show="!$APIIsExist" @click="onLabelNative()">
              <img :src="imageData[0].url" alt="">
            </label>
            <input type="file" id="upHead1" v-show="false" accept=".jpg, .jpeg, .png" @change="onFileChange">
          </div>
          <div v-show="imageData.length < max" class="weui-uploader__input-box" @click="addImage()">
            <label class="uploadHead" for="upHead2" v-show="!$APIIsExist" @click="onLabelNative()"></label>
            <input type="file" id="upHead2" v-show="false" accept=".jpg, .jpeg, .png" @change="onFileChange">
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { uploadFile } from '@api'
import { GetType } from '@utils/mixin'

export default {
  props: {
    images: {
      type: Array,
      default: () => []
    },
    max: {
      type: Number,
      default: 1
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: '图片上传'
    },
    size: {
      type: String,
      default: 'normal'
    }
  },
  data () {
    return {
      previewImages: [],
      activeImage: {},
      formdata: {
        filePath: ''
      },
      formdataup: [],
      popupFlag: false,
      imageData: [],
      fileFlag: true
    }
  },
  created () {
    this.imageData = [...this.images]
  },
  methods: {
    addImage () {
      if (this.fileFlag === false) {
        this.fileFlag = true
        return
      }
      this.$vux.loading.show()
      let UIAlbumBrowser = api.require('UIAlbumBrowser')
      UIAlbumBrowser.imagePicker({
        max: 1,
        styles: {
          bg: '#ff0036',
          nav: {
            bg: '#ff0036'
          }
        }
      }, (ret) => {
        if (ret.eventType === 'nextStep') {
          UIAlbumBrowser.closePicker()
          if (ret.list[0].size >= 2097152) {
            this.$vux.toast.show({position: 'buttom', type: 'text', text: '请选择图片大小不超过2M的图片'})
            this.$vux.loading.hide()
            return
          }
          var trans = api.require('trans')
          trans.decodeImgToBase64({
            imgPath: 'widget://' + ret.list[0].path
          }, (rets, err) => {
            if (rets.status) {
              // rets.base64Str 不带 base前缀'data:image/png;base64,'
              let fileObj = (function (path, name) {
                let bstr = atob(path)
                let n = bstr.length
                let u8arr = new Uint8Array(n)
                while (n--) {
                  u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], name, {
                  type: ret.list[0].suffix
                })
              })(rets.base64Str, 'headImage.' + ret.list[0].suffix)

              console.log(fileObj)
              this.onUpFile(fileObj)
            } else {
              this.$vux.loading.hide()
              this.$toastText(JSON.stringify(err.msg))
            }
          })
        }
      })
    },
    onLabelNative () {
      this.fileFlag = false
    },
    onFileChange (e) {
      this.$vux.loading.show()
      let file = e.target.files[0]
      console.log(file)
      this.onUpFile(file)
    },
    onUpFile (file) {
      var formData = new FormData()
      formData.append('img', file)
      uploadFile(formData).then(response => {
        this.imageData = []
        this.imageData.push({
          url: response.data,
          name: file.name,
          ext: GetType(file.name),
          size: file.size,
          type: file.type
        })
        this.$emit('upLoaderImage', response.data)
        this.$vux.loading.hide()
      })
    }
  }
}
</script>
<style scoped lang="less">
  @import '~vux/src/styles/weui/widget/weui-uploader/index.less';
  .weui-uploader__bd.small {
    .weui-uploader__input-box {
      margin-right: .125rem;
      margin-bottom: .125rem;
      width: 1.45rem;
      height: 1.45rem;
    }
    .weui-uploader__file {
      width: 1.5rem;
      height: 1.5rem;
      margin-right: .125rem;
      margin-bottom: .125rem;
    }
  }

  .weui-uploader__input-box {
    float: right;
    width: 1.875rem;
    height: 1.875rem;
    border: .025rem dashed #acacac;
    &:before {
      height: .75rem;
    }
    &:after {
      width: .75rem;
    }
  }

  .weui-uploader__file {
    float: right;
    width: 1.875rem;
    height: 1.875rem;
  }

  .weui-cell {
    padding: 0 !important;
  }

  .uploadHead{
    display: block;
    width: 100%;
    height: 100%;
  }
</style>
